import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  RequestMethod,
} from "@nestjs/common";

import IResponse, { IResponseAPI } from "@/services/response.service";

@Catch()
export class IExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const responseJson: IResponseAPI = {
      status: false,
      code: status,
      timestamp: Date.now(),
      message: exception instanceof Error ? exception.message : "System error",
      data: null,
      __info: {
        params:
          request.method === RequestMethod.GET ? request.query : request.body,
        path: request.url,
        method: request.method,
      },
    };
    return response.json(IResponse.build(responseJson));
  }
}
